<template>
  <div class="calorie-menu-container">
    <!-- 头部信息 -->
    <div class="header-card">
      <h2 class="title">
        今日的体重为 <span class="highlight">{{ weight }}</span>kg，
        今日的基础代谢值为 <span class="highlight">{{ bmr }}</span>kcal，
        今日的剩余可摄入热量为 <span class="highlight">{{ rest_bmr }}</span>kcal
      </h2>
      <el-progress
          :percentage="currentStep / totalCategories * 100"
          :status="currentStep === totalCategories ? 'success' : 'process'"
          class="progress-bar"
      ></el-progress>
      <p class="step-info">
        <span v-if="currentStep <= totalCategories">步骤 {{ currentStep }}/{{
            totalCategories
          }}: {{ currentCategory.label }}
          <span class="limit-tip">({{
              currentCategory.limit === 0 ? '不限制' : '最多选择' + currentCategory.limit + '种'
            }})</span>
        </span>
        <span v-else>已完成所有分类选择，进入热量汇总计算</span>
      </p>
    </div>

    <!-- 分步选择区域 -->
    <div v-if="currentStep <= totalCategories" class="step-content" transition="fade">
      <!-- 限选提示（超出时显示，仅当limit>0时） -->
      <el-alert
          v-if="currentCategory.limit > 0 && currentSelected.length > currentCategory.limit"
          type="warning"
          closable="false"
          :message="`当前分类最多只能选择${currentCategory.limit}种食物，请调整选择`"
          class="limit-alert"
      ></el-alert>

      <el-table
          :data="filteredFoods"
          height="400"
          border
          stripe
          @selection-change="handleSelectionChange"
          class="food-table"
          ref="foodTable"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="食物名称" prop="name" width="180"></el-table-column>
        <el-table-column label="每克热量(kcal)" prop="caloriePer1g" align="center" sortable></el-table-column>
        <el-table-column label="说明" prop="description"></el-table-column>
      </el-table>

      <div class="button-group">
        <el-button
            @click="prevStep"
            :disabled="currentStep === 1"
            type="default"
            icon="el-icon-arrow-left"
        >
          上一步
        </el-button>
        <el-button
            @click="nextStep"
            type="primary"
            icon="el-icon-arrow-right"
            :loading="isSubmitting"
            :disabled="(currentCategory.limit > 0 && currentSelected.length > currentCategory.limit) || currentSelected.length === 0"
        >
          {{ currentStep === totalCategories ? '完成选择' : '下一步' }}
        </el-button>
      </div>
    </div>

    <!-- 汇总输入区域 -->
    <div v-else class="summary-content" transition="fade">
      <h3 class="summary-title">已选食物汇总 & 热量计算</h3>

      <!-- 空状态提示 -->
      <div v-if="selectedFoods.length === 0" class="empty-summary">
        <el-empty description="暂无选中的食物，请返回重新选择"></el-empty>
        <el-button @click="prevStep" type="primary" style="margin-top: 16px;">返回选择</el-button>
      </div>

      <!-- 分组汇总表单 -->
      <el-form :model="form" label-width="120px" class="summary-form" v-else>
        <div v-for="(foodGroup, categoryName) in groupedFoods" :key="categoryName" class="food-group">
          <div class="group-header" @click="toggleGroup(categoryName)">
            <i class="el-icon"
               :class="{ 'el-icon-arrow-down': groupExpanded[categoryName], 'el-icon-arrow-right': !groupExpanded[categoryName] }"></i>
            <span class="group-title">{{ categoryName }}</span>
            <span class="group-count">({{ foodGroup.length }}/{{ getCategoryLimitText(categoryName) }})</span>
          </div>

          <div class="group-content" v-if="groupExpanded[categoryName]">
            <div class="food-item" v-for="(food, index) in foodGroup" :key="food.id">
              <div class="food-item-header">
                <span class="item-index">{{ index + 1 }}.</span>
                <span class="item-name">{{ food.name }}</span>
              </div>

              <div class="food-item-content">
                <div class="content-item">
                  <el-tag class="content-value">每100g热量{{ food.caloriePer1g }} kcal</el-tag>
                </div>

                <div class="content-item">
                  <label class="content-label">实际摄入克重：</label>
                  <el-input-number
                      v-model="food.gramWeight"
                      :min="1"
                      :max="1000"
                      :step="1"
                      size="small"
                      style="width: 120px;"
                      @change="calculateTotalCalorie"
                  ></el-input-number>
                  <span class="unit">g</span>
                </div>

                <div class="content-item">
                  <label class="content-label">热量贡献：</label>
                  <el-tag type="success" class="content-value">
                    {{ (food.gramWeight * food.caloriePer1g).toFixed(1) }} kcal
                  </el-tag>
                </div>
              </div>
            </div>

            <div class="group-total">
              组内总热量：<span class="group-total-value">{{ calculateGroupTotal(foodGroup).toFixed(1) }} kcal</span>
            </div>
          </div>
        </div>

        <div class="total-calorie-card">
          <p>本次总摄入热量：<span class="total-value">{{ totalCalorie.toFixed(1) }} kcal</span></p>
          <p>基础代谢占比：<span class="ratio-value">{{ bmr ? (totalCalorie / bmr * 100).toFixed(1) : '0.0' }}%</span>
          </p>
        </div>

        <div class="submit-group">
          <el-button @click="resetAll" type="default">重新选择</el-button>
          <el-button @click="submitDiet" type="success" icon="el-icon-check">提交饮食记录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: 'FoodPickView',
  data() {
    return {
      weight: null,
      bmr: null,
      rest_bmr: null,
      today: moment(new Date()).utcOffset(8).format('YYYY-MM-DD'),

      // 食物分类配置（初始化为空，通过接口获取）
      categories: [],

      currentStep: 1,
      totalCategories: 0,  // 改为动态从接口数据获取
      selectedFoods: [],    // 存储所有已选食物（去重）
      currentSelected: [],  // 当前步骤选中的食物
      isSubmitting: false,
      totalCalorie: 0,
      form: {},
      groupExpanded: {},
    };
  },
  computed: {
    currentCategory() {
      // 优化：确保currentStep超出范围时的安全处理
      return this.categories.find(cat => cat.id === this.currentStep) || this.categories[0] || {
        label: '未加载',
        limit: 0,  // 默认不限制
        foods: []
      };
    },
    groupedFoods() {
      return this.selectedFoods.reduce((groups, food) => {
        const categoryName = food.categoryLabel || '其他';
        if (!groups[categoryName]) {
          groups[categoryName] = [];
          this.$set(this.groupExpanded, categoryName, true);
        }
        groups[categoryName].push(food);
        return groups;
      }, {});
    },
    filteredFoods() {
      // 关键优化：过滤掉已在任何分类中选中的食物，避免重复选择
      const selectedFoodIds = this.selectedFoods.map(f => f.id);
      return this.currentCategory.foods.filter(food => !selectedFoodIds.includes(food.id));
    }
  },
  created() {
    this.get_today_bmr();
    this.get_food_cal_list();
  },
  methods: {
    // 处理选择变化，严格控制选择数量（0表示不限制）
    handleSelectionChange(val) {
      const {limit} = this.currentCategory;

      // 限制为0时不截断，直接保留所有选择
      if (limit === 0) {
        this.currentSelected = val;
        return;
      }

      // 限制>0时，超出部分自动截断
      if (val.length > limit) {
        this.currentSelected = val.slice(0, limit);
        this.$message.warning(`当前分类最多只能选择${limit}种食物，已自动截断多余选择`);

        // 同步表格选中状态（取消超出部分的选择）
        this.$nextTick(() => {
          this.syncTableSelection();
        });
      } else {
        this.currentSelected = val;
      }
    },

    // 同步表格选中状态（解决选择超出限制后表格状态不一致问题）
    syncTableSelection() {
      if (!this.$refs.foodTable) return;

      this.$refs.foodTable.clearSelection();
      this.currentSelected.forEach(food => {
        this.$refs.foodTable.toggleRowSelection(food, true);
      });
    },

    // 下一步（优化去重逻辑和状态同步，支持0限制）
    nextStep() {
      const {limit} = this.currentCategory;


      // 2. 限制校验：仅当limit>0时检查是否超限
      if (limit > 0 && this.currentSelected.length > limit) {
        this.$message.error(`请遵守选择限制，最多选择${limit}种食物`);
        return;
      }

      // 3. 保存当前分类选中的食物（双重去重保障）
      this.currentSelected.forEach(food => {
        const exists = this.selectedFoods.some(f => f.id === food.id);
        if (!exists) {
          const newFood = {
            ...food,
            categoryLabel: this.currentCategory.label,
            gramWeight: 100  // 默认100g
          };
          this.selectedFoods.push(newFood);
        }
      });

      // 4. 进入下一步或汇总页
      if (this.currentStep < this.totalCategories) {
        this.currentStep++;
        this.currentSelected = [];
        this.$nextTick(() => {
          this.$refs.foodTable?.clearSelection();
        });
        this.$message.info(`进入 ${this.currentCategory.label} 选择`);
      } else {
        this.currentStep++;
        this.calculateTotalCalorie();
        this.currentSelected = [];
        this.$message.success('已完成所有分类选择，现在可以调整食用克重并查看热量汇总');
      }
    },

    // 上一步（优化状态回显，确保不重复、适配0限制）
    prevStep() {
      if (this.currentStep > this.totalCategories) {
        // 从汇总页返回最后一步
        this.currentStep = this.totalCategories;
      } else if (this.currentStep > 1) {
        // 从当前步骤返回上一步
        this.currentStep--;
      }

      // 回显当前步骤已选的食物（仅当前分类的已选食物）
      const categoryFoods = this.selectedFoods.filter(f => f.categoryLabel === this.currentCategory.label);

      // 0限制时全部回显，否则按限制截断
      this.currentSelected = this.currentCategory.limit === 0
          ? categoryFoods
          : categoryFoods.slice(0, this.currentCategory.limit);

      // 同步表格选中状态
      this.$nextTick(() => {
        this.syncTableSelection();
      });
    },

    // 计算总热量
    calculateTotalCalorie() {
      this.totalCalorie = this.selectedFoods.reduce((total, food) => {
        const gram = Number(food.gramWeight) || 0;
        return total + (gram * food.caloriePer1g);
      }, 0);
    },

    // 计算分组内总热量
    calculateGroupTotal(foodGroup) {
      return foodGroup.reduce((total, food) => {
        const gram = Number(food.gramWeight) || 0;
        return total + (gram * food.caloriePer1g);
      }, 0);
    },

    // 获取分类的选择限制（数值）
    getCategoryLimit(categoryName) {
      const category = this.categories.find(cat => cat.label === categoryName);
      return category?.limit ?? 0;
    },

    // 获取分类的选择限制文本（汇总页显示用）
    getCategoryLimitText(categoryName) {
      const limit = this.getCategoryLimit(categoryName);
      return limit === 0 ? '不限制' : limit + '种';
    },

    // 重置所有选择（完全清空状态）
    resetAll() {
      this.currentStep = 1;
      this.selectedFoods = [];
      this.currentSelected = [];
      this.totalCalorie = 0;
      this.groupExpanded = {};
      this.$nextTick(() => {
        this.$refs.foodTable?.clearSelection();
      });
      this.$message.info('已重置所有选择，可重新开始食物选择');
    },

    // 提交饮食记录
    async submitDiet() {
      if (this.selectedFoods.length === 0) {
        this.$message.warning('请至少选择一种食物');
        return;
      }

      const invalidFood = this.selectedFoods.find(food => !food.gramWeight || food.gramWeight < 1);
      if (invalidFood) {
        this.$message.error(`请为【${invalidFood.name}】输入有效的食用克重（至少1g）`);
        return;
      }

      this.isSubmitting = true;
      console.log(this.selectedFoods)
      try {
        const res = await this.$axios.post('/health/food/add_intake_record', this.selectedFoods)
        if (res.data.code === 200) {
          this.$message.success('饮食记录提交成功！');
          this.isSubmitting = false;
        } else {
          this.$message.error(res.data.message)
        }
      } catch (err) {
        this.$message.error('后端错误：', err)
      }


    },

    // 切换分组折叠/展开
    toggleGroup(categoryName) {
      this.$set(this.groupExpanded, categoryName, !this.groupExpanded[categoryName]);
    },

    // 获取今日总基础代谢值
    async get_today_bmr() {
      try {
        const res = await this.$axios.post('/health/weight/get_bmr', {date: this.today});
        if (res.data.code === 200) {
          this.bmr = Number(res.data.data.bmr).toFixed(2);
          this.rest_bmr = Number(res.data.data.rest_bmr);
          this.weight = Number(res.data.data.weight);
          this.$message.success('更新基础代谢值成功');
        }
      } catch (error) {
        this.$message.error('获取基础代谢值失败');
        console.error('BMR获取失败:', error);
      }
    },

    // 获取所有可选的食物列表（优化limit默认值为0）
    async get_food_cal_list() {
      try {
        const res = await this.$axios.get('/health/food/get_food_kcal_list');
        if (res.data.code === 200) {
          // 处理分类数据：确保id连续、limit默认0（不限制）
          this.categories = res.data.data.map((cat, index) => ({
            ...cat,
            id: index + 1,  // 确保id从1开始连续（避免步骤切换异常）
            limit: typeof cat.limit === 'number' ? cat.limit : 0,  // 默认为0（不限制）
            foods: cat.foods || []  // 确保foods数组存在
          })).filter(cat => cat.foods.length > 0);  // 过滤掉无食物的分类

          this.totalCategories = this.categories.length;
          // 初始化第一步（如果有分类）
          if (this.categories.length > 0 && this.currentStep === 1) {
            this.$nextTick(() => {
              this.syncTableSelection();
            });
          }
        }
      } catch (error) {
        this.$message.error('获取食物列表失败');
        console.error('食物列表获取失败:', error);
      }
    }
  },
  mounted() {
    this.calculateTotalCalorie();
  }
};
</script>

<style scoped>
/* 新增过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.calorie-menu-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  font-family: "Microsoft YaHei", sans-serif;
}

.header-card {
  background: #f5fafe;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.title {
  font-size: 18px;
  color: #1989fa;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.highlight {
  color: #e53e3e;
  font-weight: 700;
  margin: 0 4px;
}

.progress-bar {
  margin-bottom: 8px;
}

.step-info {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.step-content, .summary-content {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.food-table {
  margin-bottom: 24px;
}

.limit-alert {
  margin-bottom: 16px;
}

.button-group, .submit-group {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.summary-title {
  font-size: 16px;
  color: #1989fa;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.total-calorie-card {
  background: #fdf2f8;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  display: flex;
  gap: 32px;
  align-items: center;
}

.total-value, .ratio-value {
  color: #e53e3e;
  font-size: 18px;
  font-weight: 700;
  margin-left: 8px;
}

/* 空状态样式 */
.empty-summary {
  text-align: center;
  padding: 48px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-card, .step-content, .summary-content {
    padding: 16px;
  }

  .total-calorie-card {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>

<!-- 分组相关样式 -->
<style>
.summary-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

/* 分组容器 */
.food-group {
  margin-bottom: 20px;
  border-radius: 6px;
  border: 1px solid #e6e6e6;
  overflow: hidden;
}

/* 分组标题栏 */
.group-header {
  background: #f8f9fa;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s;
}

.group-header:hover {
  background: #f0f2f5;
}

.group-icon {
  color: #409eff;
  margin-right: 10px;
  font-size: 16px;
}

.group-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  flex: 1;
}

.group-count {
  color: #999;
  font-size: 14px;
}

/* 组内内容区域 */
.group-content {
  padding: 16px;
}

/* 食物项容器 */
.food-item {
  border-bottom: 1px dashed #e6e6e6;
  padding: 16px 0;
}

.food-item:last-child {
  border-bottom: none;
}

/* 食物项头部（序号+名称） */
.food-item-header {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.item-index {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background: #409eff;
  color: #fff;
  border-radius: 50%;
  margin-right: 10px;
  font-size: 14px;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

/* 食物项内容（横向排列） */
.food-item-content {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: center;
}

.content-item {
  display: flex;
  align-items: center;
}

.content-label {
  color: #666;
  font-size: 14px;
  margin-right: 8px;
  white-space: nowrap;
}

.content-value {
  color: #333;
  font-size: 14px;
  font-weight: 400;
}

.unit {
  margin-left: 8px;
  color: #999;
  font-size: 14px;
}

/* 分组小计 */
.group-total {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  font-size: 14px;
  color: #666;
}

.group-total-value {
  color: #409eff;
  font-weight: 500;
  margin: 0 4px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .food-item-content {
    gap: 16px;
  }

  .content-item {
    width: 100%;
  }
}
</style>